package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.ApUnlikeBehaviorMapper;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApUnlikeBehaviorService;
import com.heima.model.Utils.threadlocal.AppThreadLocalUtils;
import com.heima.model.behavior.dto.UnLikesBehaviorDto;
import com.heima.model.behavior.pojo.ApBehaviorEntry;
import com.heima.model.behavior.pojo.ApUnlikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojo.ApUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Created by ZYJ on 2021/6/5 0:15
 */
@Service
public class ApUnlikeBehaviorServiceImpl extends ServiceImpl<ApUnlikeBehaviorMapper, ApUnlikesBehavior>implements ApUnlikeBehaviorService {
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;
    /**
     * 不喜欢或取消不喜欢
     * @param dto
     * @return
     */
    @Override
    public ResponseResult unlike(UnLikesBehaviorDto dto) {
        if(dto == null ||dto.getArticleId() == null ||(dto.getType() !=0 &&dto.getType()!=1)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = AppThreadLocalUtils.getUser();
        if(user == null || user.getId() == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApBehaviorEntry behaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), null);
        if(behaviorEntry == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUnlikesBehavior unlikeBehavior = this.getOne(Wrappers.<ApUnlikesBehavior>lambdaQuery()
                .eq(ApUnlikesBehavior::getArticleId, dto.getArticleId())
                .eq(ApUnlikesBehavior::getEntryId, dto.getType())
        );
        if(dto.getType() == 0 && unlikeBehavior == null){
            //保存不喜欢操作
            ApUnlikesBehavior apUnlikesBehavior = new ApUnlikesBehavior();
            apUnlikesBehavior.setEntryId(behaviorEntry.getId());
            apUnlikesBehavior.setArticleId(dto.getArticleId());
            apUnlikesBehavior.setType((short)0);
            apUnlikesBehavior.setCreatedTime(new Date());
            this.save(apUnlikesBehavior);
        }else {
            this.remove(Wrappers.<ApUnlikesBehavior>lambdaQuery()
                    .eq(ApUnlikesBehavior::getArticleId,dto.getArticleId())
                    .eq(ApUnlikesBehavior::getEntryId,behaviorEntry.getId())
            );
        }
        return ResponseResult.okResult();
    }
}
